import Vue from 'vue'
import VueRouter from 'vue-router'
import index from '../views/index.vue'
import Users from '../components/users.vue'
import Notice from '../components/notice.vue'
import Job from '../components/job.vue'
import Meals from '../components/meals.vue'
import MealsClassify from '../components/mealsClassify.vue'
import MealsOrder from '../components/mealsOrder.vue'
import RepairOrder from '../components/repairOrder.vue'
import Login from '../views/login.vue'
import AddDish from '../components/addDish.vue'
import Lose from '../views/lose.vue'
import Shop from '../components/shop.vue'
import Rate from '../components/rate.vue'
import SignUp from '../components/signUp.vue'

Vue.use(VueRouter)

const white = ['/login','/lose']

const routes = [
  {
    path: '/',
    name: 'index',
    component: index,
    redirect: '/users',
    children: [
      {
        path: '/addDish',
        component: AddDish
      },
      {
        path: '/users',
        component: Users
      },
      {
        path: '/job',
        component: Job
      },
      {
        path: '/notice',
        component: Notice
      },
      {
        path: '/meals',
        component: Meals
      },
      {
        path: '/mealsClassify',
        component: MealsClassify
      },
      {
        path: '/mealsOrder',
        component: MealsOrder
      },
      {
        path: '/repairOrder',
        component: RepairOrder
      },
      {
        path: '/shop',
        component: Shop
      },
      {
        path: '/rate',
        component: Rate
      },
      {
        path: '/signUp',
        component: SignUp
      },
    ]
  },
  {
    path:'/login',
    component:Login,
    name:'login'
  },
  {
    path:'/lose',
    component:Lose,
    name:'lose',
  }
]

const router = new VueRouter({
  routes
})

// 挂在路由导航守卫 防止用户在没有登陆的情况下直接访问主页
router.beforeEach((to, from, next) => {
  //to将要访问的路径  如果是login则直接放行
  if(white.indexOf(to.path) !== -1){
    return next()
  }

  //获取localStorage中的用户信息
  const token = window.sessionStorage.getItem('token')
  //判断用户信息是否为空  如果为空强制跳转至登陆界面  如果不为空则跳转至主页
  if(!token){
    return next('/login')
  }
  next()
})

export default router
